package net.lgpage.http;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import net.lgpage.http.ExceptionAsyncTask.HttpNotingReturnException;
import net.lgpage.util.CustomMultipartEntity;
import net.lgpage.util.CustomMultipartEntity.ProgressListener;
import net.lgpage.util.PromptTool.TagTool;
import net.lgpage.util.StreamTool;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import com.matriq.cloudmanager.MyApp;

public class HttpClientUtil {

	private static String TAG = "JavaWebServer";

	public static String postAppendUrl(String appendurl)
			throws Exception {
		return postAppendUrl(appendurl, null);
	}

	public static int ConnectionTimeout = 5000;
	public static int SoTimeout = 21000;

	public static String postUrl(String url, Map<String, String> map)
			throws Exception {
		HttpPost hp = new HttpPost(url);
		TagTool.d(TAG, url);
		TagTool.d(TAG, "dataput:" + map);
		DefaultHttpClient hc = new DefaultHttpClient();
		if (MyApp.getApp().getCookieStore() != null) {
			hc.setCookieStore(MyApp.getApp().getCookieStore());
		}
		HttpParams params = null;
		params = hc.getParams();
		HttpConnectionParams.setConnectionTimeout(params, ConnectionTimeout);
		HttpConnectionParams.setSoTimeout(params, SoTimeout);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		if (map != null)
			for (Entry<String, String> e : map.entrySet()) {
				nvps.add(new BasicNameValuePair(e.getKey(), e.getValue()));
			}
		hp.setParams(params);
		hp.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		hp.setHeader("Charset", "UTF-8");
		HttpResponse hr = null;
		hr = hc.execute(hp);
		hr.setHeader("Charset", "UTF-8");
		if (hr.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			CookieStore cook = hc.getCookieStore();
			if (cook != null) {
				MyApp.getApp().setCookieStore(cook);
			}
			String strResult = null;
			InputStream is = hr.getEntity().getContent();
			byte[] bs = StreamTool.getBytes(is);
			strResult = new String(bs);
			TagTool.d(TAG, strResult);
			if (strResult.length() == 0) {
				throw new HttpNotingReturnException();
			}
			return strResult;
		} else {
			throw new HttpException("閿欒鐘舵�佺爜:"
					+ hr.getStatusLine().getStatusCode());
		}
	}

	public static String postAppendUrl(String appendurl, Map<String, String> map)
			throws Exception {
		return postUrl(MyApp.getApp().getUrl() + appendurl, map);
	}

	public static String postFiles(String url, Map<String, String> map,
			Map<String, File> filemap, ProgressListener listener) throws Exception{
		HttpPost post = new HttpPost(url);
		TagTool.d(TAG, url);
		TagTool.d(TAG, "dataput:" + map);
		TagTool.d(TAG, "filedataput:" + filemap);
		DefaultHttpClient hc = new DefaultHttpClient();
		if (MyApp.getApp().getCookieStore() != null) {
			hc.setCookieStore(MyApp.getApp().getCookieStore());
		}
		HttpParams params = null;
		params = hc.getParams();
		post.setHeader("Charset", "UTF-8");
		HttpConnectionParams.setConnectionTimeout(params, ConnectionTimeout);
		//HttpConnectionParams.setSoTimeout(params, SoTimeout);
		CustomMultipartEntity entity = new CustomMultipartEntity(listener);
		if(filemap!=null)
		for (Entry<String, File> e : filemap.entrySet()) {
			if (e.getValue() != null && e.getValue().exists()) {
				entity.addPart(e.getKey(), new FileBody(e.getValue()));
			}
		}
		if(map!=null)
		for (Entry<String, String> e : map.entrySet()) {
			entity.addPart(e.getKey(),
					new StringBody(e.getValue(), Charset.forName("UTF-8")));
		}
		post.setEntity(entity);
		
		HttpResponse response = hc.execute(post);
		response.setHeader("Charset", "UTF-8");
		int stateCode = response.getStatusLine().getStatusCode();
		StringBuffer sb = new StringBuffer();
		if (stateCode == HttpStatus.SC_OK) {
			HttpEntity result = response.getEntity();
			if (result != null) {
				InputStream is = result.getContent();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is));
				String tempLine;
				while ((tempLine = br.readLine()) != null) {
					sb.append(tempLine);
				}
			}
		}
		post.abort();
		TagTool.d(TAG, sb.toString());
		return sb.toString();
	}

	public static String postAppendUrlFiles(String appendurl,
			Map<String, String> map, Map<String, File> filemap)
			throws Exception {
		return postFiles(MyApp.getApp().getUrl()+ appendurl, map, filemap, null);
	}
	public static String postAppendUrlFiles(String appendurl,
			Map<String, String> map, Map<String, File> filemap, ProgressListener listener)
			throws Exception {
		return postFiles(MyApp.getApp().getUrl()+ appendurl, map, filemap, listener);
	}
	
}
